<template>
  <a-spin :spinning="loading">
    <div class="p24 page-miH page-bgBack">
      <div class="headerBox">
        <div style="display: flex; flex-flow: row">
          <selectCompanyGroup
            class="mt4 mr20"
            :hasLeftIcon="true"
            :siteIds.sync="siteId"
            :siteName.sync="siteName"
            :selectTreeId.sync="selectTreeId"
            :type.sync="type"
          />
          <a-month-picker class="mr20" :default-value="now ? moment(now, 'YYYY-MM') : null" placeholder="选择月份" @change="monthChange" />
          <a-select style="width: 150px" placeholder="状态筛选" @change="approStatusChange" allowClear>
            <a-select-option value="0"> 待结算 </a-select-option>
            <a-select-option value="1"> 审批中 </a-select-option>
            <a-select-option value="2"> 审批驳回 </a-select-option>
            <a-select-option value="5"> 已通过待结算 </a-select-option>
            <a-select-option value="6"> 已结算 </a-select-option>
          </a-select>
        </div>

        <div>
          <a-button type="primary" v-if="false" @click="mergBilling" style="margin-right: 10px"> 合并账单</a-button>
          <a-button type="primary" @click="creatBilling">
            <img style="width: 16px; height: 16px; margin-right: 5px; margin-bottom: 2px" src="../../../assets/img/zhangd.png" />
            生成账单
          </a-button>
        </div>
      </div>

      <template v-if="list.length === 0">
        <a-empty style="margin-top: 100px" />
      </template>
      <template v-else>
        <div v-for="(item, i) in list" :key="i">
          <div v-if="item.companyName" style="font-size: 16px; font-weight: 500; color: #000; margin-top: 25px; margin-bottom: -10px">
            {{ item.companyName }}
          </div>
          <div style="display: flex; justify-content: space-between">
            <div class="fix-item-wrapper">
              <div :class="[item.isConfirm ? 'fix-item-one' : 'fix-item-one2']">
                <p class="fix-item-name">{{ getBillName(item.billName) }}</p>
                <div
                  v-if="getSubT(item.approStatus) !== ''"
                  style="flex-flow: row; width: 100%; display: flex; align-items: center; justify-content: center; margin-top: 10px"
                >
                  <p
                    :style="[
                      { textAlign: 'center' },
                      {
                        color: getColor(item.approStatus)
                      },
                      { background: getBackground(item.approStatus) },
                      { borderRadius: '3px 3px 3px 3px' },
                      { paddingLeft: '5px' },
                      { paddingRight: '5px' },
                      { border: getBorder(item.approStatus) },
                      { fontSize: '11px' },
                      { marginRight: '8px' },
                      { cursor: 'pointer' }
                    ]"
                  >
                    {{ getSubT(item.approStatus) }}
                  </p>
                </div>
              </div>
              <div :class="[item.subjectType === '社保账单' || item.subjectType === '公积金账单' ? 'fix-item-two-shebao' : 'fix-item-two']">
                <div>
                  <p class="childpProjectName">{{ getTitle(item.subjectType, 0) }}</p>
                  <p v-if="getTitle(item.subjectType, 0) !== '计薪人数'" class="childContentName">¥{{ getCost(item, 0) }}元</p>
                  <p v-else class="childContentName">{{ getCost(item, 0) }}人</p>
                </div>
              </div>
              <div :class="[item.subjectType === '社保账单' || item.subjectType === '公积金账单' ? 'fix-item-two-shebao' : 'fix-item-two']">
                <div>
                  <p class="childpProjectName">{{ getTitle(item.subjectType, 1) }}</p>
                  <p class="childContentName">¥{{ getCost(item, 1) }}元</p>
                </div>
              </div>
              <div class="fix-item-two-shebao" v-if="item.subjectType === '社保账单' || item.subjectType === '公积金账单'">
                <div>
                  <p class="childpProjectName">滞纳金</p>
                  <p class="childContentName">¥{{ item.fine ? item.fine : 0 }}元</p>
                </div>
              </div>
              <div :class="[item.subjectType === '社保账单' || item.subjectType === '公积金账单' ? 'fix-item-two-shebao' : 'fix-item-two']">
                <div>
                  <p class="childpProjectName">{{ getTitle(item.subjectType, 2) }}</p>
                  <p class="childContentName">¥{{ getCost(item, 2) }}元</p>
                </div>
              </div>
              <div
                v-if="item.isConfirm"
                :class="[item.subjectType === '社保账单' || item.subjectType === '公积金账单' ? 'fix-item-two-shebao' : 'fix-item-two']"
              >
                <div>
                  <p class="childpProjectName">实际支付金额</p>
                  <p class="childContentName">¥{{ item.finalAmount ? item.finalAmount : 0 }}元</p>
                </div>
              </div>
              <div :class="[item.isConfirm ? 'fix-item-two2' : 'fix-item-two3']">
                <a-dropdown placement="bottomLeft">
                  <a-icon type="ellipsis" class="primary_color w24 mr20" style="font-size: 30px" />
                  <a-menu slot="overlay">
                    <a-menu-item :disabled="!item.userApproId" @click="handleMenuClick(0, item)">查看审核流程</a-menu-item>
                    <a-menu-item :disabled="item.approStatus === 1 || item.approStatus === 3" @click="handleMenuClick(1, item)">
                      发起审批</a-menu-item
                    >
                    <a-menu-item
                      :disabled="(item.approStatus !== 5 && item.approStatus !== 0) || item.isMerge"
                      @click="handleMenuClick(3, item)"
                    >
                      账单结算</a-menu-item
                    >
                    <a-menu-item :disabled="item.approStatus === 1" @click="handleMenuClick(2, item)"> 删除</a-menu-item>
                  </a-menu>
                </a-dropdown>
                <div class="fix-item-one-end" style="cursor: pointer" @click="onDetail(item)">
                  {{
                    item.autoSystem
                      ? "查看详情"
                      : item.annexUrl
                      ? item.annexUrl.indexOf(".jpg") !== -1 ||
                        item.annexUrl.indexOf(".jpeg") !== -1 ||
                        item.annexUrl.indexOf(".png") !== -1
                        ? "预览附件"
                        : "下载附件"
                      : "无附件"
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <a-modal title="合并账单" :visible="isMergConfirmPlan" width="560px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="mergConfirmOk"> 确定 </a-button>
        </template>
        <div>
          <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }">
            <a-form-item label="选择用工单位分组" required>
              <a-select style="width: 305px" placeholder="请选择" @change="handleChange2">
                <a-select-option v-for="(item, index) in templatesListGroup" :key="index" :value="index">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <div style="width: 305px">
                <a-tag v-for="(item, index) in group" :key="index">{{ item.name }}</a-tag>
              </div>
            </a-form-item>

            <a-form-item label="账单时间" required>
              <a-month-picker
                style="width: 305px"
                :default-value="billingD != null ? moment(billingD, 'YYYY-MM') : null"
                @change="onStopYearMonthChange"
              />
            </a-form-item>
            <a-form-item label="合并账单类型" required>
              <a-radio-group @change="onCheckOutChange" v-model="billingType" style="width: 320px">
                <a-radio value="shebao"> 社保账单 </a-radio>
                <a-radio value="gongjijin"> 公积金账单 </a-radio>
                <a-radio value="xinzi"> 薪资账单 </a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <a-modal title="账单结算" :visible="BillConfirm" width="560px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="BillConfirmOk"> 确定 </a-button>
        </template>
        <div>
          <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 20px; font-size: 15px; font-weight: 700">
            {{ currentItem ? currentItem.tempCompanyName + currentItem.billName : "" }}
          </div>
          <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }">
            <a-form-item label="人数" v-if="currentItem ? getTitle(currentItem.subjectType, 0) !== '计薪人数' : false">
              <a-input
                suffix="人"
                :disabled="true"
                :default-value="
                  currentItem ? (getTitle(currentItem.subjectType, 0) !== '计薪人数' ? currentItem.number : getCost(currentItem, 0)) : 0
                "
              />
            </a-form-item>
            <a-form-item :label="currentItem ? getTitle(currentItem.subjectType, 0) : ''">
              <a-input suffix="元" :disabled="true" :default-value="currentItem ? getCost(currentItem, 0) : 0" />
            </a-form-item>
            <a-form-item :label="currentItem ? getTitle(currentItem.subjectType, 1) : ''">
              <a-input suffix="元" :disabled="true" :default-value="currentItem ? getCost(currentItem, 1) : 0" />
            </a-form-item>
            <a-form-item :label="currentItem ? getTitle(currentItem.subjectType, 2) : ''">
              <a-input suffix="元" :disabled="true" :default-value="currentItem ? getCost(currentItem, 2) : 0" />
            </a-form-item>
            <a-form-item label="实际付款额">
              <a-input-number
                :min="0"
                suffix="元"
                :default-value="onBillChange(currentItem ? getCost(currentItem, 2) : 0)"
                @change="onBillChange"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <a-modal title="生成账单" :visible="isConfirmPlan" width="530px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="confirmOk"> 确定 </a-button>
        </template>
        <div>
          <div class="baseInfo-item2">
            <div :class="isSysBilling ? 'onwork2' : 'onwork'" style="margin-right: 20px" @click="tabClick(true)">
              <img style="width: 30px; height: 28px; margin-right: 15px" src="../../../assets/img/xitongc.png" />
              <span>从系统中生成账单</span>
            </div>
            <div :class="isSysBilling ? 'onwork' : 'onwork2'" @click="tabClick(false)">
              <img style="width: 30px; height: 28px; margin-right: 15px" src="../../../assets/img/ziji.png" />
              自己创建账单
            </div>
          </div>
          <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }">
            <a-form-item label="选择用工单位" required>
              <a-select
                allowClear
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                style="width: 250px"
                placeholder="请选择"
                @change="handleChange"
                mode="multiple"
              >
                <a-select-option v-for="(item, index) in templatesList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="账单时间" required>
              <a-month-picker
                style="width: 250px"
                :default-value="billingD != null ? moment(billingD, 'YYYY-MM') : null"
                @change="onStopYearMonthChange"
              />
            </a-form-item>
            <a-form-item label="生成账单类型" required>
              <a-select :default-value="billingType" style="width: 250px" @change="handleSelectChange">
                <a-select-option value="shebao"> 社保账单 </a-select-option>
                <a-select-option value="gongjijin"> 公积金账单 </a-select-option>
                <a-select-option value="xinzi"> 薪资账单 </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'shebao'" label="单位社保" required>
              <a-input-number
                placeholder="请输入单位社保金额"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="DanWeiSheBao"
                v-model="DanWeiSheBao"
                @change="onDanWeiSheBaoChange"
              />
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'shebao'" label="个人社保" required>
              <a-input-number
                placeholder="请输入个人社保金额"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="GeRenSheBao"
                v-model="GeRenSheBao"
                @change="onGeRenSheBaoChange"
              />
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'gongjijin'" label="单位公积金" required>
              <a-input-number
                placeholder="请输入单位公积金金额"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="DanWeiGongJiJin"
                v-model="DanWeiGongJiJin"
                @change="onDanWeiGongJiJinChange"
              />
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'gongjijin'" label="个人公积金" required>
              <a-input-number
                placeholder="请输入个人公积金金额"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="GeRenGongJiJin"
                v-model="GeRenGongJiJin"
                @change="onGeRenGongJiJinChange"
              />
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'xinzi'" label="计薪人数" required>
              <a-input-number
                placeholder="请输入计薪人数"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="JiXinRenShu"
                v-model="JiXinRenShu"
                @change="onJiXinRenShuChange"
              />
            </a-form-item>
            <a-form-item v-if="!isSysBilling && billingType === 'xinzi'" label="总实发工资" required>
              <a-input-number
                placeholder="请输入总实发工资"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="ZongShiFaGongZi"
                v-model="ZongShiFaGongZi"
                @change="onZongShiFaGongZiChange"
              />
            </a-form-item>

            <a-form-item v-if="!isSysBilling && billingType === 'xinzi'" label="总缴税" required>
              <a-input-number
                placeholder="请输入总缴税金额"
                style="width: 250px"
                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                :default-value="ZongJiaoShui"
                v-model="ZongJiaoShui"
                @change="onZongJiaoShuiChange"
              />
            </a-form-item>

            <a-form-item v-if="!isSysBilling" label="账单附件">
              <div style="padding-top: 10px">
                <Uploading :srcData.sync="url" @change="onFileChange" :limit="1"></Uploading>
                <UploadSiteFile
                  v-show="false"
                  ref="uploadTool"
                  :limit="1"
                  :default-value="url"
                  accept=".doc,.docx,.xls,.xlsx,.pdf,.zip,.rar,.jpg,.jpeg,.png"
                />
              </div>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <!-- 删除通知 -->
      <a-modal
        title="删除通知"
        :visible="deleteVisible"
        class="notice-modal"
        width="468px"
        @ok="confirmDelete()"
        @cancel="deleteVisible = false"
      >
        <div class="deleteline">
          <p>
            <a-icon type="exclamation-circle" />
            确定删除这条账单？
          </p>
        </div>
      </a-modal>
      <a-modal title="发起审批" :visible="isMergConfirmPlan2" width="500px" :destroy-on-close="true" @cancel="handleCancel">
        <template slot="footer">
          <a-button @click="handleCancel"> 取消 </a-button>
          <a-button key="submit" type="primary" @click="mergConfirmOk2"> 确定 </a-button>
        </template>
        <div>
          <a-form :label-col="{ span: 9 }" :wrapper-col="{ span: 12 }">
            <a-form-item label="账单时间" required>
              <div style="font-size: 14px; font-weight: 500; color: #000">
                {{ tempItem ? tempItem.year + "年" + tempItem.month + "月" : "" }}
              </div>
            </a-form-item>
            <a-form-item label="审批账单类型" required>
              <div style="font-size: 14px; font-weight: 500; color: #000">
                {{ tempItem ? tempItem.subjectType : "" }}
              </div>
            </a-form-item>
            <a-form-item label="用工单位" required>
              <a-select style="width: 220px" placeholder="请选择用工单位" @change="handleCompyChange" v-model="companyId">
                <a-select-option v-for="(item, index) in comanyListGroup" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="账单审批模板" required>
              <a-select
                v-model="tempTemplate"
                style="width: 220px"
                placeholder="请选择审批模板"
                @change="handleChange3"
                :disabled="!companyId"
              >
                <a-select-option v-for="(item, index) in templatesListGroup2" :key="index" :value="item.id">
                  {{ item.typeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
      <div
        v-if="total !== 0"
        style="display: flex; flex-flow: row; align-items: center; width: 100%; justify-content: flex-end; margin-top: 15px"
      >
        <a-pagination
          :page-size-options="pageSizeOptions"
          show-size-changer
          :default-current="pageNo"
          :total="total"
          @showSizeChange="onShowSizeChange"
        />
      </div>
    </div>
  </a-spin>
</template>
<script>
import {
  generatedBills,
  costBills,
  costBillIdDelete,
  launchApproval,
  listAllCompany,
  costBillSites,
  listAllCompanyGroup,
  getModelList,
  selectCompanyByCostBillId,
  confirmCostBill
} from "@/api/billing/billing";
import { getMonthlySalaryXinZi, batchArchive } from "@/api/wages/monthly";
import { UploadSiteFile } from "xqjr-plugin-common";
import selectCompanyGroup from "@/components/SelectCompany";
import { isContainByString } from "@/utils/index";
import moment from "moment";
import { mapGetters, mapState } from "vuex";
export default {
  components: {
    selectCompanyGroup,
    UploadSiteFile,
    Uploading: () => import("@/components/Uploading/uploading")
  },
  data() {
    return {
      zongBill: 0,
      currentItem: undefined,
      BillConfirm: false,
      isMergConfirmPlan: false,
      isMergConfirmPlan2: false,
      templatesList: [],
      templatesListGroup: [],
      templatesListGroup2: [],
      url: "",
      pageSizeOptions: ["10", "20", "50", "100"],
      deleteVisible: false,
      currentitem: undefined,
      xinziName: "",
      billingType: "shebao",
      isSysBilling: true,
      billingD: null,
      isConfirmPlan: false,
      list: [],
      dataList: [],
      size: "default",
      loading: false,
      now: null,
      status: null,
      action: "",
      combined: {},
      nameOrIdCard: null,
      DanWeiSheBao: 0,
      GeRenSheBao: 0,
      DanWeiGongJiJin: 0,
      GeRenGongJiJin: 0,
      JiXinRenShu: 0,
      ZongShiFaGongZi: 0,
      ZongJiaoShui: 0,
      pageNo: 1,
      pageSize: 20,
      total: 0,
      isContainByString,
      seletComyId: [],
      group: [],
      siteId: undefined,
      siteName: undefined,
      selectTreeId: "-1",
      companyId: undefined,
      tempTemplate: undefined,
      comanyListGroup: [],
      tempItem: undefined
    };
  },
  watch: {
    siteName(sitName) {
      this.pageNo = 1;
      this.getCostBills();
    },
    selectTreeId(selectTreeId) {}
  },

  created() {
    this.selectTreeId = this.SelectedId;
    this.now = moment();
  },
  computed: {
    ...mapState(["site"]),
    ...mapGetters(["permissions_site"]),
    ...mapGetters({
      SelectedId: "site/SelectedId"
    }),
    type() {
      return this.site.selectType;
    }
  },
  methods: {
    onBillChange(value) {
      this.zongBill = value;
      return value;
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    handleCompyChange(id) {
      this.companyId = id;
      this.templatesListGroup2 = [];
      this.tempTemplate = undefined;
      let type;
      if (this.tempItem.subjectType === "社保账单") {
        type = "socBill";
      } else if (this.tempItem.subjectType === "公积金账单") {
        type = "pfBill";
      } else if (this.tempItem.subjectType === "薪资账单") {
        type = "salaryBill";
      }
      // 根据公司查询模板
      getModelList(id, type).then((res) => {
        this.templatesListGroup2 = res.data;
        if (this.templatesListGroup2.length !== 0) {
          this.tempTemplate = this.templatesListGroup2[0].id;
        } else {
          this.tempTemplate = undefined;
        }
      });
    },
    handleChange3(id) {
      // 选择模板
      this.tempTemplate = id;
    },
    mergConfirmOk2() {
      // 发起审批
      if (!this.companyId) {
        this.$message.success("请选择用工单位");
        return;
      }
      if (!this.tempTemplate) {
        this.$message.success("请选择审批模板");
        return;
      }
      this.isMergConfirmPlan2 = false;
      launchApproval({
        companyId: this.companyId,
        costBillId: this.tempItem.id,
        flowId: this.tempTemplate
      }).then((res) => {
        this.tempItem.approStatus = res.data.status;
        this.$message.success("已发起审批");
      });
    },
    getBillName(name) {
      const f = name.indexOf("]");

      return name.substring(f + 1, name.length);
    },
    getSubT(name) {
      switch (name) {
        case 0:
          return "待结算";
        case 1:
          return "审批中";
        case 2:
          return "审批驳回";
        case 5:
          return "已通过待结算";
        case 6:
          return "已结算";
        default:
          return "";
      }
    },
    getColor(status) {
      switch (status) {
        case 0:
          return "#F7B500";
        case 1:
          return "#4282FF";
        case 2:
          return "#FF7085";
        case 5:
          return "#F7B500";
        case 6:
          return "#24CDAA";
        default:
          return "#F7B500";
      }
    },
    getBackground(status) {
      switch (status) {
        case 0:
          return "#F7B50036";
        case 1:
          return "#4282FF36";
        case 2:
          return "#FF708536";
        case 5:
          return "#F7B50036";
        case 6:
          return "#24CDAA36";
        default:
          return "#F7B50036";
      }
    },
    getBorder(status) {
      switch (status) {
        case 0:
          return "1px solid #F7B500";
        case 1:
          return "1px solid #4282FF";
        case 2:
          return "1px solid #FF7085";
        case 5:
          return "1px solid #F7B500";
        case 6:
          return "1px solid #24CDAA";
        default:
          return "1px solid #F7B500";
      }
    },
    onCheckOutChange(checkedValues) {
      this.billingType = checkedValues.target.value;
    },
    handleChange(e, a) {
      this.seletComyId = e;
    },
    handleChange2(e) {
      this.seletComyId = this.templatesListGroup[e].id;
      this.group = this.templatesListGroup[e].companyList;
      // console.log(this.templatesListGroup)
      // console.log(this.seletComyId)
    },
    onFileChange(urls) {
      console.log(urls);
    },
    confirmDelete() {
      this.deleteVisible = false;
      costBillIdDelete(this.currentitem.id).then((res) => {
        this.$message.success("账单删除成功");
        this.getCostBills();
      });
    },

    getTitle(value, index) {
      switch (value) {
        case "社保账单":
          if (index === 0) {
            return "个人社保";
          } else if (index === 1) {
            return "单位社保";
          } else if (index === 2) {
            return "总缴费";
          } else {
            break;
          }
        case "公积金账单":
          if (index === 0) {
            return "个人公积金";
          } else if (index === 1) {
            return "单位公积金";
          } else if (index === 2) {
            return "总缴费";
          } else {
            break;
          }
        case "薪资账单":
          if (index === 0) {
            return "计薪人数";
          } else if (index === 1) {
            return "总缴税";
          } else if (index === 2) {
            return "总实发工资";
          } else {
            break;
          }
      }
    },
    getCost(value, index) {
      switch (value.subjectType) {
        case "社保账单":
          if (index === 0) {
            return value.personalSocAmount;
          } else if (index === 1) {
            return value.companySocAmount;
          } else if (index === 2) {
            return value.totalAmount;
          } else {
            break;
          }
        case "公积金账单":
          if (index === 0) {
            return value.personalPfAmount;
          } else if (index === 1) {
            return value.companyPfAmount;
          } else if (index === 2) {
            return value.totalAmount;
          } else {
            break;
          }
        case "薪资账单":
          if (index === 0) {
            return value.calculateSalaryNumber ? value.calculateSalaryNumber : 0;
          } else if (index === 1) {
            return value.totalTax ? value.totalTax : 0;
          } else if (index === 2) {
            return value.totalAmount ? value.totalAmount : 0;
          } else {
            break;
          }
      }
    },
    onShowSizeChange(current, pageSize) {
      this.pageNo = current;
      this.pageSize = pageSize;
      this.getCostBills();
    },
    listAllCompany() {
      listAllCompany().then((res) => {
        this.templatesList = res.data;
      });
    },
    listAllCompanyGroup() {
      listAllCompanyGroup().then((res) => {
        this.templatesListGroup = res.data;
      });
    },
    getCostBills() {
      var param = {
        pageNo: this.pageNo,
        pageSize: this.pageSize
      };
      if (this.selectTreeId !== "-1") {
        // 总公司
        if (this.type === "group") {
          param.isMerge = true;
        } else {
          param.isMerge = false;
        }
        param.companyId = this.selectTreeId;
      } else {
        param.isMerge = false;
      }

      if (this.now) {
        param.year = moment(this.now).format("YYYY");
        param.month =
          moment(this.now).format("MM") === "10" ? moment(this.now).format("MM") : moment(this.now).format("MM").replace("0", "");
      }
      if (this.status) {
        param.status = parseInt(this.status);
      }
      costBills(param).then((res) => {
        this.pageNo = res.data.pageNo === 0 ? 1 : res.data.pageNo;
        // this.pageSize = res.data.pageSize;
        this.total = res.data.entityCount;
        if (res.data.entities === null) {
          this.list = [];
        } else {
          this.list = [];
          this.$nextTick(() => {
            var count = res.data.entities.length;
            var name = null;
            for (var i = 0; i < count; i++) {
              res.data.entities[i].tempCompanyName = res.data.entities[i].companyName;
              if (!name || res.data.entities[i].companyName !== name) {
                name = res.data.entities[i].companyName;
              } else {
                res.data.entities[i].companyName = null;
              }
            }
            this.list = res.data.entities;
          });
        }
      });
    },

    onDanWeiSheBaoChange(value) {
      this.DanWeiSheBao = value;
    },
    onGeRenSheBaoChange(value) {
      this.GeRenSheBao = value;
    },
    onDanWeiGongJiJinChange(value) {
      this.DanWeiGongJiJin = value;
    },
    onGeRenGongJiJinChange(value) {
      this.GeRenGongJiJin = value;
    },
    onJiXinRenShuChange(value) {
      this.JiXinRenShu = value;
    },
    onZongShiFaGongZiChange(value) {
      this.ZongShiFaGongZi = value;
    },
    onZongJiaoShuiChange(value) {
      this.ZongJiaoShui = value;
    },
    tabClick(value) {
      this.isSysBilling = value;
    },
    handleSelectChange(value) {
      this.billingType = value;
      this.url = "";
      this.DanWeiSheBao = 0;
      this.GeRenSheBao = 0;
      this.DanWeiGongJiJin = 0;
      this.GeRenGongJiJin = 0;
      this.JiXinRenShu = 0;
      this.ZongShiFaGong = 0;
      this.ZongJiaoShui = 0;
    },
    handleSelectGZChange(value) {
      this.xinziName = value;
    },
    onStopYearMonthChange(date, dateString) {
      this.billingD = date;
    },
    handleCancel() {
      this.isConfirmPlan = false;
      this.isMergConfirmPlan = false;
      this.isMergConfirmPlan2 = false;
      this.BillConfirm = false;
    },
    getType() {
      switch (this.billingType) {
        case "shebao":
          return "社保账单";
        case "gongjijin":
          return "公积金账单";
        case "xinzi":
          return "薪资账单";
      }
    },
    mergConfirmOk() {
      if (!this.billingD) {
        this.$message.error("请选择账单时间");
        return;
      }
      // console.log(this.seletComyId)
      if (this.seletComyId.length === 0) {
        this.$message.error("请选择用工单位分组");
        return;
      }

      const param = {
        year: moment(this.billingD).format("YYYY"),
        month: moment(this.billingD).format("MM"),
        subjectType: this.getType(),
        autoSystem: true,
        companyGroupId: this.seletComyId
      };

      costBillSites(param).then((res) => {
        this.isMergConfirmPlan = false;
        this.$message.success("账单已合成");
        this.pageNo = 1;
        this.getCostBills();
      });
    },
    BillConfirmOk() {
      if (this.currentItem) {
        const param = {
          costBillId: this.currentItem.id,
          finalAmount: this.zongBill
        };

        confirmCostBill(param).then((res) => {
          this.handleCancel();
          this.getCostBills();
        });
      }
    },
    confirmOk() {
      if (!this.billingD) {
        this.$message.error("请选择账单时间");
        return;
      }
      if (this.seletComyId.length === 0) {
        this.$message.error("请选择用工单位");
        return;
      }
      const param = {
        year: moment(this.billingD).format("YYYY"),
        month: moment(this.billingD).format("MM"),
        subjectType: this.getType(),
        autoSystem: this.isSysBilling,
        companyIdList: this.seletComyId
      };
      var that = this;
      this.$confirm({
        title: "即将创建账单",
        content:
          param.subjectType === "薪资账单"
            ? "是否确认生成本月薪资账单，一旦生成工资表将会归档，本月工资表不可进行更改"
            : "是否确认生成本月" + param.subjectType + "账单，一旦生成，本月" + param.subjectType + "将不可进行更改",
        okText: "确认",
        onOk() {
          if (!that.isSysBilling) {
            // 自己创建
            switch (that.billingType) {
              case "shebao":
                param.companySocAmount = that.DanWeiSheBao;
                param.personalSocAmount = that.GeRenSheBao;
                break;
              case "gongjijin":
                param.companyPfAmount = that.DanWeiGongJiJin;
                param.personalPfAmount = that.GeRenGongJiJin;
                break;
              case "xinzi":
                param.calculateSalaryNumber = that.JiXinRenShu;
                param.totalAmount = that.ZongShiFaGongZi;
                param.totalTax = that.ZongJiaoShui;
                break;
            }
            if (that.url) {
              // 附件
              param.annexUrl = that.url;
            }

            generatedBills(param).then((res) => {
              that.isConfirmPlan = false;
              that.$message.success("账单已生成");
              that.pageNo = 1;
              that.getCostBills();
            });
          } else {
            // 查询是否有归档
            if (param.subjectType === "薪资账单") {
              let selsid = "";
              for (var i = 0; i < that.seletComyId.length; i++) {
                if (i === that.seletComyId.length - 1) {
                  selsid += that.seletComyId[i];
                } else {
                  selsid += that.seletComyId[i] + ",";
                }
              }
              getMonthlySalaryXinZi({
                companyIds: selsid,
                monthly: param.month,
                yearly: param.year
              })
                .then((res) => {
                  if (!res.data || res.data.entities) {
                    const weiGuiDang = [];
                    for (var i = 0; i < res.data.entities.length; i++) {
                      if (!res.data.entities[i].isArchive) {
                        weiGuiDang.push(res.data.entities[i].id);
                      }
                    }
                    // 有未归档模板
                    if (weiGuiDang.length !== 0) {
                      that.$confirm({
                        title: "发现未归档薪资模板",
                        content: "是否确认归档？归档后工资表所有数据 不允许删除或更改",
                        okText: "确认",
                        onOk() {
                          batchArchive(weiGuiDang).then((res) => {
                            if (res.success) {
                              generatedBills(param).then((res) => {
                                that.isConfirmPlan = false;
                                that.$message.success("账单已生成");
                                that.pageNo = 1;
                                that.getCostBills();
                              });
                            }
                          });
                        },
                        onCancel() {}
                      });
                    } else {
                      generatedBills(param).then((res) => {
                        that.isConfirmPlan = false;
                        that.$message.success("账单已生成");
                        that.pageNo = 1;
                        that.getCostBills();
                      });
                    }
                  } else {
                    generatedBills(param).then((res) => {
                      that.isConfirmPlan = false;
                      that.$message.success("账单已生成");
                      that.pageNo = 1;
                      that.getCostBills();
                    });
                  }
                })
                .catch((error) => {
                  console.log("Error", error);
                  that.loading = false;
                });
            } else {
              generatedBills(param).then((res) => {
                that.isConfirmPlan = false;
                that.$message.success("账单已生成");
                that.pageNo = 1;
                that.getCostBills();
              });
            }
          }
        },
        onCancel() {}
      });
    },
    onDetail(item) {
      if (item.autoSystem) {
        this.$router.push({
          path: this.isContainByString("settlementAdmin") ? "/settlementAdmin/billing/billingDetail" : "/settlement/billing/billingDetail",
          query: {
            item: JSON.stringify(item)
          }
        });
      } else {
        console.log(item.annexUrl);
        if (item.annexUrl) {
          // 下载
          window.open(item.annexUrl + `?token=${this.$store.state.auth.token}`);
        }
      }
    },
    handleMenuClick(index, item) {
      switch (index) {
        case 0:
          if (item.userApproId) {
            this.$router.push(`/approval/detail/${item.userApproId}/read`);
          }
          break;
        case 1: // 重新发起审批
          this.tempItem = item;

          this.isMergConfirmPlan2 = true;
          this.companyId = undefined;
          this.tempTemplate = undefined;
          // 拉取账单的用工单位
          selectCompanyByCostBillId({ costBillId: this.tempItem.id }).then((res) => {
            this.comanyListGroup = res.data;
            if (this.comanyListGroup.length !== 0) {
              this.companyId = this.comanyListGroup[0].id;

              // 拉取模板
              this.handleCompyChange(this.companyId);
            } else {
              this.companyId = undefined;
            }
          });

          break;
        case 2:
          this.deleteVisible = true;
          this.currentitem = item;
          break;
        case 3:
          this.currentItem = item;
          this.BillConfirm = true;
          break;
      }
    },
    // 创建账单
    creatBilling() {
      this.listAllCompany();
      this.isConfirmPlan = true;
      this.billingType = "shebao";
      this.isSysBilling = true;
      this.url = "";
      this.DanWeiSheBao = 0;
      this.GeRenSheBao = 0;
      this.DanWeiGongJiJin = 0;
      this.GeRenGongJiJin = 0;
      this.JiXinRenShu = 0;
      this.ZongShiFaGong = 0;
      this.ZongJiaoShui = 0;
      this.billingD = null;
      this.seletComyId = [];
    },
    // 合并账单
    mergBilling() {
      this.listAllCompanyGroup();
      this.isMergConfirmPlan = true;
      this.group = [];
      this.billingD = null;
      this.seletComyId = [];
      this.billingType = "shebao";
    },
    monthChange(e) {
      console.log(e);
      this.now = e;
      this.pageNo = 1;
      this.getCostBills();
    },
    approStatusChange(e) {
      this.status = e;
      this.getCostBills();
    }
  }
};
</script>
<style lang="scss" scoped>
.iconfont {
  color: var(--primary);
}
.onwork {
  background-color: #f4f6fa;
  border-radius: 5px;
  // border: 1px solid #e8e8e8;
  padding: 25px 18px;
  display: flex;
  flex-flow: row;
  align-items: center;
  width: 200px;
  justify-content: center;
  cursor: pointer;
}
.onwork2 {
  background-color: #ffffff;
  border-radius: 5px;
  border: 1px solid var(--primary);
  padding: 25px 18px;
  display: flex;
  flex-flow: row;
  align-items: center;
  justify-content: center;
  width: 200px;
  cursor: pointer;
}

.headerBox {
  display: flex;
  width: "100%";
  justify-content: space-between;
}
.fix-item-wrapper {
  width: 100%;
  display: flex;
  height: 110px;
  background: #ffffff;
  border-radius: 5px;
  margin-top: 25px;
  align-items: center;
  border: 1px solid #e8e8e8;
  display: flex;
  .childpProjectName {
    width: 100px;
    font-size: 14px;
    font-weight: 300;
    color: #9c9c9c;
  }
  .childContentName {
    display: flex;
    justify-content: space-between;
    font-size: 22px;
    font-weight: 500;
    color: #333333;
    margin-bottom: 0px;
  }
  .fix-item-one {
    height: 60%;
    display: flex;
    align-self: center;
    justify-content: center;
    flex-flow: column;
    width: 45%;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-one2 {
    height: 60%;
    display: flex;
    align-self: center;
    justify-content: center;
    flex-flow: column;
    width: 35%;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-one-end {
    // height: 40px;
    // width: 15%;

    font-size: 14px;
    color: var(--primary);
  }
  .fix-item-one-end-point {
    display: flex;
    align-self: center;

    font-size: 8px;
    color: var(--primary);
    padding-bottom: 5px;
    margin-left: 35px;
    cursor: pointer;
  }
  .fix-item-two {
    padding-left: 35px;

    width: 45%;
    height: 60%;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-two-shebao {
    padding-left: 35px;

    width: 32%;
    height: 60%;
    padding-right: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-right: 1px solid #e8e8e8;
  }
  .fix-item-two2 {
    flex-flow: row;
    width: 30%;
    height: 60%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .fix-item-two3 {
    flex-flow: row;
    width: 23%;
    height: 60%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .fix-item-name {
    width: 100%;
    font-size: 18px;
    font-weight: 500;
    color: #3c3d43;
    text-align: center;
    margin-bottom: 0px;
  }
}

.operation {
  padding: 25px 0;
  display: flex;
  justify-content: space-between;
}
.iconStyle {
  color: var(--primary);
  margin-right: 8px;
}

.baseInfo-item2 {
  width: 100%;
  display: flex;
  flex-flow: row;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
</style>
